/**
 @ Name：layui.customPage 自定义分页插件
 @ Author：wwk
 */

layui.define(['form', 'table'], function(exports) { //假如该组件依赖 layui.form
    var $ = layui.$,
        form = layui.form,
        table = layui.table,
        doc = document,
        id = 'getElementById',
        tag = 'getElementsByTagName'

    //字符常量
    , MOD_NAME = 'customPage', DISABLED = 'custom-disabled', ELEM = 'layui-customPage', HIDE = 'custom-hide', THIS = 'custom-this'
        //外部接口
        , customPage = {
            index: layui.customPage ? (layui.customPage.index + 10000) : 0

            //设置全局项
            ,
            set: function(options) {
                var that = this;
                that.config = $.extend({}, that.config, options);
                return that;
            }

            //事件监听
            ,
            on: function(events, callback) {
                return layui.onevent.call(this, MOD_NAME, events, callback);
            }
        }

    //操作当前实例
    , thisIns = function() {
        var that = this,
            options = that.config,
            id = options.id || options.index;

        return {
            reload: function(options) {
                that.reload.call(that, options);
            },
            config: options
        }
    }

    //构造器
    , Class = function(options) {
        var that = this;
        that.index = ++customPage.index;
        that.config = $.extend({}, that.config, customPage.config, options);
        that.render();
    };

    //默认配置
    Class.prototype.config = {
        layout: ['limit', 'prev', 'skip', 'next', 'count'], //联动层级
        //其他参数
        //……
    };

    // 分页视图
    Class.prototype.view = function() {
        var that = this,
            config = that.config,
            firstPage = 1,
            lastPage = 1;

        config.count = config.count | 0; // 数据总数
        config.curr = (config.curr | 0) || 1; //当前页

        // 每页条数的选择项
        config.limits = typeof config.limits === 'object' ?
            config.limits :
            [10, 20, 30, 40, 50];
        config.limit = (config.limit | 0) || 6; // 默认条数

        // 总页数
        config.pages = Math.ceil(config.count / config.limit) || 1;
        // 最后页数
        lastPage = config.pages;

        // 当前页不能超过总页数
        if (config.curr > config.pages) {
            config.curr = config.pages;
        }

        config.prev = 'prev' in config ? config.prev : '&#x4E0A;&#x4E00;&#x9875;'; //上一页文本
        config.next = 'next' in config ? config.next : '&#x4E0B;&#x4E00;&#x9875;'; //下一页文本

        // 视图片段
        var views = {
            // 每页条数
            limit: function() {
                var options = [
                    '<div class="custom-unselect custom-form-select">',
                    '<div class="custom-select-title">',
                    '<input type="text" value="' + that.config.limit + '" readonly="" class="custom-input custom-unselect">',
                    '<span class="custom-edge-container"><i class="custom-edge"></i></span>',
                    '</div>',
                    '<dl class="custom-anim custom-anim-upbit custom-hide" style="">'
                ];

                layui.each(config.limits, function(index, item) {
                    options.push(
                        '<dd lay-value="' + item + '"' +
                        'class="' + (item === config.limit ? 'custom-this' : '') + '">' +
                        item + '</dd>'
                    );
                });
                return options.join('') + '</dl></div>'
            }(),

            // 跳转到首页
            skipFirst: function() {
                return ('<a href="javascript:;" class="custom-skip-first' + (config.curr == 1 ? (' ' + DISABLED) : '') + '" data-page="' + firstPage + '">' +
                    '<img src="../images/first-page@2x.png" height="12px" alt="首页"></img>' +
                    '</a>');
            }(),

            // 上一页
            prev: function() {
                return config.prev ?
                    ('<a href="javascript:;" class="layui-customPage-prev' + (config.curr == 1 ? (' ' + DISABLED) : '') + '" data-page="' + (config.curr - 1) + '">' +
                        '<img src="../images/left-page@2x.png" height="12px" alt="上一页"></img></a>') :
                    '';
            }(),

            // 跳页区域
            skip: function() {
                return ['<span class="layui-customPage-skip layui-customPage-item">&#x7B2C;', '<input readonly="readonly" type="text" min="1" value="' + config.curr + '" class="baoinouName layui-input">', '&#x9875;', '</span>'].join('');
            }(),


            // 下一页
            next: function() {
                return config.next ?
                    ('<a href="javascript:;" class="layui-customPage-next' + (config.curr == config.pages ? (' ' + DISABLED) : '') + '" data-page="' + (config.curr + 1) + '">' +
                        '<img src="../images/right-page@2x.png" height="12px" alt="上一页"></img></a>') :
                    '';
            }(),

            // 跳转到尾页 
            skipLast: function() {
                return ('<a href="javascript:;" class="custom-skip-last' + (config.curr == lastPage ? (' ' + DISABLED) : '') + '" data-page="' + lastPage + '">' +
                    '<img src="../images/last-page@2x.png" height="12px" alt="尾页"></img>' +
                    '</a>');
            }()
        };

        return $(['<div class="layui-box layui-customPage layui-laypage-' + (config.theme ? (
                /^#/.test(config.theme) ? 'molv' : config.theme
            ) : 'default') + '" id="layui-laypage-' + config.index + '">',
            function() {
                var plate = [];
                layui.each(config.layout, function(index, item) {
                    if (views[item]) {
                        plate.push(views[item])
                    }
                });
                return plate.join('');
            }(),
            '<div class="layui-customPage-pageInfo">',
            // '<span>当前显示' + ((config.curr - 1) * config.limit + 1) + '-' + config.curr * config.limit + '</span>',
            '<span>共' + config.count + '条记录</span>',
            '</div></div>'
        ].join(''));
    }

    //跳页的回调
    Class.prototype.jump = function(elem, isskip) {
        if (!elem) return;
        var that = this,
            config = that.config,
            $ = layui.jquery,
            reElem = elem.find('.custom-form-select'),
            selectElem = elem.find('.custom-select-title'),
            input = selectElem.find('input'),
            dl = reElem.find('dl'),
            dds = dl.children('dd'),
            achilds = elem.children('a'),
            skip = function() {
                var curr = input.value.replace(/\s|\D/g, '') | 0;
                if (curr) {
                    config.curr = curr;
                    that.render();
                }
            }
            //展开下拉
            ,
            showDown = function() {
                reElem.addClass('custom-form-selected');
                dds.removeClass(HIDE);
                //初始选中样式
                dds.eq(that.config.limits[that.config.limit]).addClass(THIS).siblings().removeClass(THIS);
            }

        //隐藏下拉
        , hideDown = function() {
            reElem.removeClass('custom-form-selected');
            input.blur();
        };

        //点击箭头
        reElem.on('click', '.custom-edge-container', function(e) {
            reElem.hasClass('custom-form-selected') ? (
                hideDown()
            ) : (
                showDown()
            );
        });

        if (isskip) return skip();

        // 首页 尾页 上一页 下一页
        elem.on('click', '.custom-skip-first, .layui-customPage-prev, .layui-customPage-next, .custom-skip-last', function() {
            var curr = this.getAttribute('data-page') | 0;
            if (curr < 1 || curr > config.pages) return;
            config.curr = curr;
            that.render();
        });

        //选择
        reElem.on('click', 'dl dd', function() {
            var othis = $(this),
                value = othis.attr('lay-value');
            input.val(othis.text());
            if (config.curr * value > config.count) {
                config.curr = Math.ceil(config.count / value);
            }
            config.limit = parseInt(othis.text(), 10);
            othis.addClass(THIS);
            othis.siblings().removeClass(THIS);
            hideDown(true);
            that.render();
            return false;
        });
    };

    //输入页数字控制
    Class.prototype.skip = function(elem) {
        if (!elem) return;
        var that = this,
            input = elem[tag]('input')[0];
        if (!input) return;
        laypage.on(input, 'keyup', function(e) {
            var value = this.value,
                keyCode = e.keyCode;
            if (/^(37|38|39|40)$/.test(keyCode)) return;
            if (/\D/.test(value)) {
                this.value = value.replace(/\D/, '');
            }
            if (keyCode === 13) {
                that.jump(elem, true)
            }
        });
    };

    //请求loading
    Class.prototype.loading = function(hide) {
        var that = this,
            options = that.config;
        if (options.loading) {
            if (hide) {
                that.layInit && that.layInit.remove();
                delete that.layInit;
                that.layBox.find(ELEM_INIT).remove();
            } else {
                that.layInit = $(['<div class="layui-table-init">', '<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>', '</div>'].join(''));
                that.layBox.append(that.layInit);
            }
        }
    };

    //渲染数据
    Class.prototype.renderData = function(data, tableReloadData) {
        var that = this,
            options = that.config;
        // console.log(that, options, 'renderData');
    }

    //获得数据
    Class.prototype.pullData = function(curr) {
        var that = this,
            options = that.config,
            request = options.request;

        if (options.url) { //Ajax请求
            var params = {};
            params[request.pageName] = curr;
            params[request.limitName] = options.limit;

            //参数
            var data = $.extend(params, options.where);
            if (options.contentType && options.contentType.indexOf("application/json") == 0) { //提交 json 格式
                data = JSON.stringify(data);
            }
            that.loading();
            $.ajax({
                type: options.method || 'get',
                url: options.url,
                contentType: options.contentType,
                data: data,
                dataType: 'json',
                headers: options.headers || {},
                success: function(res) {
                    //如果有数据解析的回调，则获得其返回的数据
                    if (typeof options.parseData === 'function') {
                        res = options.parseData(res) || res;
                    }
                    //检查数据格式是否符合规范
                    if (!res['flag']) {
                        // that.renderForm();
                        // that.errorView(
                        //   res[response.msgName] ||
                        //   ('返回的数据不符合规范，正确的成功状态码应为："'+ response.statusName +'": '+ response.statusCode)
                        // );
                    } else {
                        options.count = res['total'];
                        options.time = (new Date().getTime() - that.startTime) + ' ms'; //耗时（接口请求+视图渲染）
                        that.render(true);
                    }
                    typeof options.done === 'function' && options.done(res, curr, res['data']);
                },
                error: function(e, m) {

                }
            });
        } else if (options.data && options.data.constructor === Array) { //已知数据
            var res = {},
                startLimit = curr * options.limit - options.limit

            res[response.dataName] = options.data.concat().splice(startLimit, options.limit);
            res[response.countName] = options.data.length;

            //记录合计行数据
            if (typeof options.totalRow === 'object') {
                res[response.totalRowName] = $.extend({}, options.totalRow);
            }

            that.renderData(res, curr, res[response.countName]), sort();
            that.setColsWidth();
            typeof options.done === 'function' && options.done(res, curr, res[response.countName]);
        }
    };

    //渲染视图
    Class.prototype.render = function(notPull) {
        var that = this,
            options = that.config,
            view = that.view(),
            notPull = notPull || false;

        options.elem = $(options.elem);
        options.elem.html(view);
        if (!notPull) {
            that.pullData(options.curr);
        }

        that.jump(view);
        // that.skip(view);
    }

    //核心入口
    customPage.render = function(options) {
        var ins = new Class(options);
        return thisIns.call(ins);
    };

    //加载组件所需样式
    layui.link('../lib/customPage/custom-page.css?v=1', function() {
        //样式加载完毕的回调

    }, 'customPage'); //此处的“customPage”要对应 customPage.css 中的样式： html #layuicss-customPage{}

    exports('customPage', customPage);
});